﻿using System.Data;
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI;
using System.Collections;

namespace Marbles.Core.Web.Controls
{
    [ToolboxData("<{0}:PopupMenu runat=server></{0}:PopupMenu>")]
    public class PopupMenu : WebControl
    {
        [MergableProperty(false)]
        [DefaultValue("")]
        [Category("Default")]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public PopupMenuItemCollection Items
        {
            get
            {
                if (this._items == null) { this._items = new PopupMenuItemCollection(); }
                return this._items;
            }
        }

        [Category("Appearance")]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ShadowFilterSettings Shadow
        {
            get
            {
                object obj = ViewState["ShadowSettings"];
                if (obj == null) { ViewState["ShadowSettings"] = new ShadowFilterSettings(); obj = ViewState["ShadowSettings"]; }
                return (ShadowFilterSettings)obj;
            }
            set { ViewState["ShadowSettings"] = value; }
        }

        [Category("Appearance")]
        public Color MenuHighlightBackColor
        {
            get
            {
                object obj = ViewState["MenuHighlightBackColor"];
                if (obj == null) { return System.Drawing.SystemColors.Highlight; }
                return (Color)obj;
            }
            set { ViewState["MenuHighlightBackColor"] = value; }
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }

        protected override string TagName
        {
            get
            {
                return "div";
            }
        }

        [Category("Appearance")]
        public Unit MenuItemHeight
        {
            get
            {
                object obj = ViewState["MenuItemHeight"];
                if (obj == null) { return Unit.Empty; }
                return (Unit)obj;
            }
            set { ViewState["MenuItemHeight"] = value; }
        }

        [Category("Appearance")]
        public Unit Left
        {
            get
            {
                object obj = ViewState["Left"];
                if (obj == null) { return Unit.Empty; }
                return (Unit)obj;
            }
            set { ViewState["Left"] = value; }
        }

        [Category("Appearance")]
        public Unit Top
        {
            get
            {
                object obj = ViewState["Top"];
                if (obj == null) { return Unit.Empty; }
                return (Unit)obj;
            }
            set { ViewState["Top"] = value; }
        }

        [Category("Appearance")]
        public Color MenuHighlightForeColor
        {
            get
            {
                object obj = ViewState["MenuHighlightForeColor"];
                if (obj == null) { return System.Drawing.SystemColors.MenuHighlight; }
                return (Color)obj;
            }
            set { ViewState["MenuHighlightForeColor"] = value; }
        }

        public event CommandEventHandler ItemClicked;

        private PopupMenuItemCollection _items = null;

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.ClientScript.IsClientScriptBlockRegistered("PopupMenu" + this.ClientID))
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "PopupMenu" + this.ClientID, GetScript(), true);
            }

            CreateMenu();
            base.OnLoad(e);
        }

        private string GetScript()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("function ShowMenu_" + this.ClientID + "(e) {");
            sb.AppendLine("var id = '" + this.ClientID + "';");
            sb.AppendLine("var ev = e;");
            sb.AppendLine("var xpos = 0;");
            sb.AppendLine("var ypos = 0;");
            sb.AppendLine("if (ev == null) {ev = event; xpos = ev.x; ypos = ev.y;} else {xpos = e.clientX; ypos = e.clientY;}");
            sb.AppendLine("document.getElementById(id).style.left = xpos + 'px';");
            sb.AppendLine("document.getElementById(id).style.top = ypos + 'px';");
            sb.AppendLine("document.getElementById(id).style.position = 'absolute';");
            sb.AppendLine("document.getElementById(id).style.display = 'block';");
            sb.AppendLine("return false;");
            sb.AppendLine("}");
            sb.AppendLine("function HideMenu_" + this.ClientID + "(e) {");
            sb.AppendLine("var id = '" + this.ClientID + "';");
            sb.AppendLine("document.getElementById(id).style.display = 'none';");
            sb.AppendLine("}");
            sb.AppendLine("document.oncontextmenu = ShowMenu_" + ClientID + ";");
            sb.AppendLine("document.onclick = HideMenu_" + ClientID + ";");
            return sb.ToString();
        }

        private void CreateMenu()
        {
            if (this.Shadow.Strength > 0)
            {
                this.Style.Remove("filter");
                this.Style.Add("filter", string.Format("progid:DXImageTransform.Microsoft.Shadow(color='{0}', Direction={1}, Strength={2})", ColorTranslator.ToHtml(Shadow.Color), Shadow.Direction, Shadow.Strength));
            }

            this.Style.Remove("display");
            this.Style.Add("display", "none");
            this.Style.Remove("position");
            this.Style.Remove("left");
            this.Style.Remove("top");
            if (!this.Left.IsEmpty) { this.Style.Add("left", this.Left.ToString()); }
            if (!this.Top.IsEmpty) { this.Style.Add("top", this.Top.ToString()); }
            this.Style.Add("position", "absolute");
            this.Style.Add("z-index", "65535");
            Table tbl = new Table();
            tbl.CellPadding = 2;
            tbl.CellSpacing = 0;
            tbl.BorderStyle = BorderStyle.None;
            tbl.Width = new Unit(100, UnitType.Percentage);
            tbl.ID = "PopupMenu";

            foreach (PopupMenuItem item in this.Items)
            {
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                LinkButton btn = new LinkButton();
                row.ID = "PopupMenuRow_" + tbl.Rows.Count.ToString();
                cell.ID = "PopupMenuRowCell_" + tbl.Rows.Count.ToString();
                row.Style.Add("cursor", "hand");
                row.ToolTip = item.Tooltip;
                if (this.MenuItemHeight != Unit.Empty) { row.Height = MenuItemHeight; }
                btn.Font.CopyFrom(this.Font);
                btn.CommandName = item.CommandName;
                btn.CommandArgument = item.CommandArgument;
                btn.AccessKey = item.AccessKey;
                btn.Text = FormatText(item.Text, item.AccessKey);
                btn.ToolTip = item.Tooltip;
                btn.ID = "PopupMenuLink_" + tbl.Rows.Count.ToString();
                btn.Style.Add("padding", "2px");
                btn.Font.Underline = false;
                btn.OnClientClick = "document.getElementById('" + this.ClientID + "').style.display = 'none';";
                btn.Command += new CommandEventHandler(PopupMenuItem_Command);
                row.ForeColor = this.ForeColor;
                btn.ForeColor = this.ForeColor;
                row.BackColor = this.BackColor;
                cell.Controls.Add(btn);
                row.Controls.Add(cell);
                tbl.Rows.Add(row);
            }

            this.Controls.Add(tbl);
            int i=0;

            foreach (TableRow row in tbl.Rows)
            {
                LinkButton btn = row.FindControl("PopupMenuLink_" + i.ToString()) as LinkButton;
                row.Attributes.Add("onmouseover", "this.style.background = '" + ColorTranslator.ToHtml(this.MenuHighlightBackColor) + "';this.style.color = '" + ColorTranslator.ToHtml(this.MenuHighlightForeColor) + "';document.getElementById('" + btn.ClientID + "').style.color = this.style.color;");
                row.Attributes.Add("onmouseout", "this.style.background = '" + ColorTranslator.ToHtml(row.BackColor) + "';this.style.color = '" + ColorTranslator.ToHtml(this.ForeColor) + "';document.getElementById('" + btn.ClientID + "').style.color = this.style.color;");
                row.Attributes.Add("onclick", "document.getElementById('" + btn.ClientID + "').onclick();");
                i += 1;
            }
        }

        private string FormatText(string value, string accesskey)
        {
            string value1 = value.Trim();
            if (accesskey == string.Empty) { return value1; }

            int charindex = value1.IndexOf(accesskey);

            if (charindex > 0)
            {
            }

            return value1;
        }

        protected void PopupMenuItem_Command(object sender, CommandEventArgs e)
        {
            this.Style.Remove("display");
            this.Style.Add("display", "none");
            if (this.ItemClicked != null)
            {
                ItemClicked(this, e);
            }
        }

    }

}
